/**
 * <p>Package : org.tea.springdata.mina.handler</p>
 * <p>E-Mail : ztlyde@gmail.com</p>
 */
package org.tea.springdata.mina.handler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

/**
 * @author: John zhang
 * @version: 0.1
 */
public class UDPServerHandler extends IoHandlerAdapter {

	// 当一个客端端连结进入时
	private static final Log log = LogFactory.getLog(ServerHandler.class);

	public void sessionOpened(IoSession session) throws Exception {
		log.info("server  : " + session.getRemoteAddress());
	}

	// 当一个客户端关闭时
	public void sessionClosed(IoSession session) {
		log.info("one server  Disconnect !");
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		if (message instanceof String) {
			String receivedMsg = (String) message;
			if ("quit".equalsIgnoreCase(receivedMsg)) {
				System.out.println("Session closed");
				session.close(true);
			}
			System.out.println("Client send message is : " + receivedMsg);

			receivedMsg = "Server response :" + receivedMsg;

			System.out.println("Successfully response to " + session.getRemoteAddress().toString());
			session.write(receivedMsg);
			// future.awaitUninterruptibly();
		}

	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		session.close(true);
	}

	// 创建 session
	public void sessionCreated(IoSession session) {

	}

}
